package IntelSpam::Filters::SpamhausFilter;

use 1.0;

use warnings;
use IntelSpam::Config;
use Data::Dumper;
use Net::DNS;
use Log::Log4perl qw(get_logger);

our $VERSION = '1.0';
our $DEBUG = 1;

our $REGISTER = ['connect'];
our $META = {
	'id' => 'spamhaus_filter',
	'name' => 'Spamhaus Filter',
	'description' => 'Spamhaus SBL+XBL Filter http://www.spamhaus.org',
	'version' => '1.0',
	'weight' => 30
	
};


our $logger = get_logger("IntelSpam::SpamhausFilter");


use constant DNSBL_XBL => 'XBL';
use constant DNSBL_SBL => 'SBL';
use constant DNSBL_PBL => 'PBL';
use constant DNSBL_ZEN => 'ZEN';
use constant DNSBL_NA => 'C';

our $resolver;


sub new($){
	bless {}, shift;
}

sub filter_connect($$$)
{
	my ($this, $ctx, $host) = @_;

	my $ip = $host;
	my $score = $ctx->getpriv()->{'score'};

	unless($host =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/){
		$ip = query($host);
	}

	unless(defined($ip)){
		$logger->error("could not resolve the host $host");
		$score->insert($META->{'id'}, $META->{'weight'}, 10);
		return;
	}

	my $res = dnsbl($ip);

	$score->insert($META->{'id'}, $META->{'weight'}, 25) if $res eq DNSBL_XBL || $res eq DNSBL_SBL || $res eq DNSBL_SBL;
	$score->insert($META->{'id'}, $META->{'weight'}, 20) if $res eq DNSBL_ZEN;
	unless ($res eq DNSBL_NA){
		$logger->info("$ip listed in $res");
	}else{
		$logger->info("$ip is not listed.");
	}

	
}

sub query($$)
{
	my $host = shift;
	$query = $resolver->search($host);

	if ($query) {
		foreach my $rr ($query->answer) {
			next unless $rr->type eq "A";
			return $rr->address;
		}
	} else {
		warn "query failed: $host\n";
	}

	undef;
}

sub dnsbl($$)
{
	my $ip = shift;
	if($ip =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/){
		my $query = $resolver->search("$4.$3.$2.$1.zen.spamhaus.org");
		$logger->info("querying Spamhaus $4.$3.$2.$1.zen.spamhaus.org...");
		if($query){
			foreach my $rr ($query->answer){
				next unless $rr->type eq "A";
				$logger->debug("spamhaus.org return --> ".$rr->address);
				if($rr->address =~ /^127\.0\.0\.(\d{1,3})$/){
					syslog('info', "$ip was found blacklisted in spamhaus ".$rr->address);
					my $suffix = int($1);
					return DNSBL_SBL if $suffix >= 2 && $suffix <= 3;
					return DNSBL_XBL if $suffix >= 4 && $suffix <= 7;
					return DNSBL_PBL if $suffix >= 10 && $suffix <= 11;
					return DNSBL_ZEN;
				}
			}
		}
	}
	DNSBL_NA;
}


sub get_registers($){
	$REGISTER;
}

sub get_meta($){
	$META;
}

sub set_cfg($$){

	$resolver = Net::DNS::Resolver->new;
}

1;

